/**  
  -- The Performance Driven Lime Project -- 

  A self adaptive tuple space for mobile agents and hosts by dynamic
  adapting tuple's replication policy.
  
  Copyright (C) 2008
  Xing Jiankuan, Pan Wenhui
  SAGroup of Tsinghua University

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received this copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
 */
package sagroup.dracots.testing;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import lime2.Location;
import sagroup.dracots.DracoTS;
import sagroup.dracots.DracoTuple;
import sagroup.dracots.FlatShareTuple;
import sagroup.dracots.TupleType;
import sagroup.dracots.policy.RPTuple;
import sagroup.dracots.policy.ReplicationPolicy;
import sagroup.util.Util;

/**
 * @author Jinxue Zhang
 * 
 */
public class RemoteReadPerPeriodAgent implements Runnable {

	private String type;
	private Location remote;
	private boolean timesup = false;
	private int opCount = 0;
	private long begin;
	private long timing;
	private DracoTS dts = null;

	private Logger LOG = Logger.getLogger(this.getClass().getName());

	// Set the policy for each type of tuple
	void applyPolicy(String type, String policy) {

		byte policyValue = 0;

		if (policy.compareTo("SO") == 0) {
			policyValue = 2;
		} else if (policy.compareTo("RC") == 0) {
			policyValue = 3;
		} else if (policy.compareTo("FR") == 0) {
			policyValue = 1;
		} else {
			System.out.println("Your policy is not supported now!");
			System.exit(0);
		}

		ReplicationPolicy rPolicy = new ReplicationPolicy(policyValue);
		System.out.println("Apply " + rPolicy + " policy for type " + type);
		if (dts != null) {
			RPTuple policy1 = new RPTuple(new TupleType(type), rPolicy);
			dts.out(policy1);
		} else {
			System.out.println("tuple space is null!");
			System.exit(0);
		}
	}

	private FlatShareTuple createRemoteTypeTemplate(String type, Location remote) {
		FlatShareTuple template = (FlatShareTuple) FlatShareTuple
				.createMatchAllTemplateByClass(FlatShareTuple.class);

		template.setType(new TupleType(type));

		template.setCurr(remote);
		template.setDest(remote);

		return template;
	}

	/**
	 * 
	 */
	public RemoteReadPerPeriodAgent(String typeName, String host, String port) {
		// TODO Auto-generated constructor stu
		this.type = typeName;
		remote = Location.build(host, Integer.valueOf(port));

		TimerTask tt = new TimerTask() {
			@Override
			public void run() {
				timesup = true;
				timing = (System.nanoTime() - begin) / 1000 / 1000;
			}
		};

		Timer timer = new Timer();

		timer.schedule(tt, AgentUtil.expTime);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub

		try {
			dts = DracoTS.get("testing");

			this.begin = System.nanoTime();
			HashMap<String, LinkedList<FlatShareTuple>> tuples = new HashMap<String, LinkedList<FlatShareTuple>>();
			while (!timesup) {
				// for (int i = 'A'; i <= 'Z'; i++) {
				// String type = String.valueOf((char) i);

				// Sleep first
				long sleeptime;
				if (opCount == 0)
					sleeptime = 35000;
				else
					sleeptime = 29000;
				System.out.println("Sleep for " + sleeptime / 1000 + "s.");
				Thread.sleep(sleeptime);

				LinkedList<FlatShareTuple> list = new LinkedList<FlatShareTuple>();

				DracoTuple[] ret = null;

				for (int readCount = 0; readCount < 10; readCount++) {
					ret = dts.rdg(createRemoteTypeTemplate(type, remote));
					if (ret != null) {
						LOG.info("Agent read tuples type/amount : " + type
								+ "/" + ret.length);
						break;
					} else {
						LOG.info("^^^^^^^^^RDG failed for " + readCount
								+ " times");
					}
				}

				for (DracoTuple t : ret) {
					list.add((FlatShareTuple) t);
				}

				tuples.put(type, list);
				opCount++;
				// }
			}

			System.out.println(this.toString() + " Agent finishs all work.");

		} catch (Exception ex) {
			System.out.println("Exception occurs : "
					+ Util.getExceptionDetail(ex));
			System.out
					.println(this.toString() + " Agent has been interrupted.");
		} finally {
			LOG.info("Agent ��Ϣ : " + this.toString() + " " + this.getInfo());
		}
	}

	public String toString() {
		String id = "Agent Remote1 " + ":" + Thread.currentThread().getName();
		String target = " ; Target remote : " + remote;
		return id + ", " + target;
	}

	private String getInfo() {
		String info = "Operation times : " + this.opCount + " Timing : "
				+ this.timing + ". Average : "
				+ ((this.opCount != 0) ? this.timing / this.opCount : null);
		return info;
	}
}
